package com.aysafety.iotdataplatformweb.controller.electromagnetic;

import com.aysafety.core.common.CheckUtils;
import com.aysafety.core.common.Common;
import com.aysafety.core.common.DataConversionUtil;
import com.aysafety.core.common.DateUtils;
import com.aysafety.iotdataplatformweb.controller.base.BaseController;
import com.aysafety.iotdataplatformweb.services.electromagnetic.ElectromagneticService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController @RequestMapping("/api/mineMonitor/realMonitor/electricRadiation/")
public class ElectromagneticController extends BaseController {

    @Autowired ElectromagneticService electromagneticService;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @RequestMapping("/intensityRealTime")
    public Map<String, Object> getIntensityRealTime(@RequestParam Map<String, Object> params,
        HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> result = new HashMap<String, Object>();
            Map<String, Object> data = new HashMap<String, Object>();
            if (!params.containsKey("mineId") || !params.containsKey("equipmentId")) {
                return this.formatReturnData("缺少参数");
            }
            String mineId = params.get("mineId").toString();
            String equipmentId = params.get("equipmentId").toString();
            String startTime = params.containsKey("startTime") ?
                params.get("startTime").toString() :
                DateUtils.getCurrentStartTime("yyyy-MM-dd HH:mm:ss");
            startTime =
                StringUtils.isNotBlank(startTime) ? startTime : DateUtils.getCurrentStartTime("yyyy-MM-dd HH:mm:ss");
            String endTime = params.containsKey("endTime") ?
                params.get("endTime").toString() :
                DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss");
            endTime = StringUtils.isNotBlank(endTime) ? endTime : DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss");
            String timeSpanStr = params.containsKey("timeSpan") ? params.get("timeSpan").toString() : "0";
            timeSpanStr = StringUtils.isNotBlank(timeSpanStr) ? timeSpanStr : "0";
            int timeSpan = Integer.parseInt(timeSpanStr);
            String timeUnit = params.containsKey("timeUnit") ? params.get("timeUnit").toString() : "s";
            timeUnit = StringUtils.isNotBlank(timeUnit) ? timeUnit : "s";
            String pageStr = params.containsKey("page") ? params.get("page").toString() : "0";
            pageStr = StringUtils.isNotBlank(pageStr) ? pageStr : "0";
            int page = Integer.parseInt(pageStr);
            String sizeStr = params.containsKey("size") ? params.get("size").toString() : "10000";
            sizeStr = StringUtils.isNotBlank(sizeStr) ? sizeStr : "10000";
            int size = Integer.parseInt(sizeStr);
            String startRow = params.containsKey("startRow") ? params.get("startRow").toString() : "";
            String firstStartRow = params.containsKey("firstStartRow") ? params.get("firstStartRow").toString() : "";
            data.put("total", electromagneticService
                .countByElectromagneticIntensity(mineId, equipmentId, startTime, endTime, timeSpan, timeUnit));
            result = Common.getData(electromagneticService
                .queryRealTimeByElectromagneticIntensity(mineId, equipmentId, startTime, endTime, timeSpan, timeUnit,
                    page, size + 1, startRow), size, startRow, firstStartRow);
            data.put("list", result.get("list"));
            data.put("firstStartRow", result.get("firstStartRow"));
            data.put("lastStartRow", result.get("lastStartRow"));
            return this.formatReturnData(data);
        } catch (Exception e) {
            logger.error("ElevatorController-getIntensityRealTime:", e);
            return this.formatReturnData(e.getMessage());
        } catch (Throwable throwable) {
            logger.error("ElevatorController-getIntensityRealTime:", throwable);
            return this.formatReturnData(throwable.getMessage());
        }
    }

    @RequestMapping("/electromagneticPulseRealTime")
    public Map<String, Object> getElectromagneticPulseRealTime(@RequestParam Map<String, Object> params,
        HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> result = new HashMap<String, Object>();
            Map<String, Object> data = new HashMap<String, Object>();
            if (!params.containsKey("mineId") || !params.containsKey("equipmentId")) {
                return this.formatReturnData("缺少参数");
            }
            String mineId = params.get("mineId").toString();
            String equipmentId = params.get("equipmentId").toString();
            String startTime = params.containsKey("startTime") ?
                params.get("startTime").toString() :
                DateUtils.getCurrentStartTime("yyyy-MM-dd HH:mm:ss");
            startTime =
                StringUtils.isNotBlank(startTime) ? startTime : DateUtils.getCurrentStartTime("yyyy-MM-dd HH:mm:ss");
            String endTime = params.containsKey("endTime") ?
                params.get("endTime").toString() :
                DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss");
            endTime = StringUtils.isNotBlank(endTime) ? endTime : DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss");
            String timeSpanStr = params.containsKey("timeSpan") ? params.get("timeSpan").toString() : "0";
            timeSpanStr = StringUtils.isNotBlank(timeSpanStr) ? timeSpanStr : "0";
            int timeSpan = Integer.parseInt(timeSpanStr);
            String timeUnit = params.containsKey("timeUnit") ? params.get("timeUnit").toString() : "s";
            timeUnit = StringUtils.isNotBlank(timeUnit) ? timeUnit : "s";
            String pageStr = params.containsKey("page") ? params.get("page").toString() : "0";
            pageStr = StringUtils.isNotBlank(pageStr) ? pageStr : "0";
            int page = Integer.parseInt(pageStr);
            String sizeStr = params.containsKey("size") ? params.get("size").toString() : "10000";
            sizeStr = StringUtils.isNotBlank(sizeStr) ? sizeStr : "10000";
//            int size = Integer.parseInt(sizeStr);
            int size = 10000;
            String startRow = params.containsKey("startRow") ? params.get("startRow").toString() : "";
            String firstStartRow = params.containsKey("firstStartRow") ? params.get("firstStartRow").toString() : "";
            data.put("total", electromagneticService
                .countByElectromagneticPulse(mineId, equipmentId, startTime, endTime, timeSpan, timeUnit));
            result = Common.getData(electromagneticService
                .queryRealTimeByElectromagneticPulse(mineId, equipmentId, startTime, endTime, timeSpan, timeUnit, page,
                    size + 1, startRow), size, startRow, firstStartRow);
            data.put("list", result.get("list"));
            data.put("firstStartRow", result.get("firstStartRow"));
            data.put("lastStartRow", result.get("lastStartRow"));
            return this.formatReturnData(data);
        } catch (Exception e) {
            logger.error("ElevatorController-getElectromagneticPulseRealTime:", e);
            return this.formatReturnData(e.getMessage());
        } catch (Throwable throwable) {
            logger.error("ElevatorController-getElectromagneticPulseRealTime:", throwable);
            return this.formatReturnData(throwable.getMessage());
        }
    }

    /**
     * @Description: 获取电磁辐射趋势预警指标A
     * @Param: [params, request, response]
     * @return: java.util.Map<java.lang.String   ,   java.lang.Object>
     * @Author: ChengQi
     * @Date: 2018/12/20
     */
    @RequestMapping("/getElectromagneticRadiationWarning")
    public Map<String, Object> getElectromagneticRadiationWarning(@RequestParam Map<String, Object> params,
        HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> data = new HashMap<String, Object>();

            //矿区id
            String mineId = DataConversionUtil.getStrFromMap("mineId", params);
            //工作面
            String workingFace = DataConversionUtil.getStrFromMap("workingFace", params);

            String startTimeStr = DataConversionUtil.getStrFromMap("startTime", params);
            //矿区id、工作面必传
            if (StringUtils.isBlank(mineId) || StringUtils.isBlank(workingFace) || StringUtils.isBlank(startTimeStr)) {
                return this.formatReturnData("缺少参数");
            }
            if (!CheckUtils.isValidDate(startTimeStr, "yyyy-MM-dd HH:mm:ss")) {
                return this.formatReturnData("日期格式不正确");
            }
            String startTime = startTimeStr.substring(0, 17) + "00";
            String defaultEndTime = DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss");
            String endTime = DataConversionUtil.getStrFromMapOrSetDefaultValue("endTime", defaultEndTime, params);

            String mStr = DataConversionUtil.getStrFromMapOrSetDefaultValue("m", "3", params);
            int m = Integer.parseInt(mStr);

            //Δt
            String dtStr = DataConversionUtil.getStrFromMapOrSetDefaultValue("dt", "30", params);
            int dt = Integer.parseInt(dtStr);

            //计算库里获取数据，如果存在数据，则直接使用，如果无则计算
            //long count = electromagneticService.countWebElectromagneticRadiationWarning(mineId, workingFace, startTime, endTime, m, dt);
            //data.put("total", count);
            List<Map<String, Object>> resultList =
                electromagneticService.queryCal(mineId, workingFace, startTime, endTime, -1, m, dt, -1);
            data.put("list", resultList);
            data.put("total", resultList.size());
            return this.formatReturnData(data);
        } catch (Exception e) {
            logger.error("ElectromagneticController-getElectromagneticRadiationWarning:", e);
            return this.formatReturnData(e.getMessage());
        } catch (Throwable throwable) {
            logger.error("ElectromagneticController-getElectromagneticRadiationWarning:", throwable);
            return this.formatReturnData(throwable.getMessage());
        }
    }

    /**
     * @Description: n小时偏差值
     * @Param: [params, request, response]
     * @return: java.util.Map<java.lang.String   ,   java.lang.Object>
     * @Author: ChengQi
     * @Date: 2018/12/20
     */
    @RequestMapping("/getDeviation") public Map<String, Object> getDeviation(@RequestParam Map<String, Object> params,
        HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> data = new HashMap<String, Object>();

            //矿区id
            String mineId = DataConversionUtil.getStrFromMap("mineId", params);
            //工作面
            String workingFace = DataConversionUtil.getStrFromMap("workingFace", params);

            String startTimeStr = DataConversionUtil.getStrFromMap("startTime", params);
            //矿区id、工作面必传
            if (StringUtils.isBlank(mineId) || StringUtils.isBlank(workingFace) || StringUtils.isBlank(startTimeStr)) {
                return this.formatReturnData("缺少参数");
            }
            if (!CheckUtils.isValidDate(startTimeStr, "yyyy-MM-dd HH:mm:ss")) {
                return this.formatReturnData("日期格式不正确");
            }
            String startTime = startTimeStr.substring(0, 17) + "00";
            String defaultEndTime = DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss");
            String endTime = DataConversionUtil.getStrFromMapOrSetDefaultValue("endTime", defaultEndTime, params);

            String mStr = DataConversionUtil.getStrFromMapOrSetDefaultValue("m", "3", params);
            int m = Integer.parseInt(mStr);

            //Δt
            String dtStr = DataConversionUtil.getStrFromMapOrSetDefaultValue("dt", "30", params);
            int dt = Integer.parseInt(dtStr);

            //n
            String nStr = DataConversionUtil.getStrFromMapOrSetDefaultValue("n", "1", params);
            int n = Integer.parseInt(nStr);

            //计算库里获取数据，如果存在数据，则直接使用，如果无则计算
            //long count = electromagneticService.countWebDeviation(mineId, workingFace, startTime, endTime, m, dt, n);
            //data.put("total", count);
            List<Map<String, Object>> resultList =
                electromagneticService.queryCal(mineId, workingFace, startTime, endTime, n, m, dt, -1);
            data.put("list", resultList);
            data.put("total", resultList.size());
            return this.formatReturnData(data);
        } catch (Exception e) {
            logger.error("ElectromagneticController-getDeviation:", e);
            return this.formatReturnData(e.getMessage());
        } catch (Throwable throwable) {
            logger.error("ElectromagneticController-getDeviation:", throwable);
            return this.formatReturnData(throwable.getMessage());
        }
    }

    /**
     * @Description: 偏离异常持续时间h
     * @Param: [params, request, response]
     * @return: java.util.Map<java.lang.String   ,   java.lang.Object>
     * @Author: ChengQi
     * @Date: 2018/12/20
     */
    @RequestMapping("/deviationLast") public Map<String, Object> deviationLast(@RequestParam Map<String, Object> params,
        HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> data = new HashMap<String, Object>();
            //矿区id
            String mineId = DataConversionUtil.getStrFromMap("mineId", params);
            //工作面
            String workingFace = DataConversionUtil.getStrFromMap("workingFace", params);

            String startTimeStr = DataConversionUtil.getStrFromMap("startTime", params);
            //矿区id、工作面必传
            if (StringUtils.isBlank(mineId) || StringUtils.isBlank(workingFace) || StringUtils.isBlank(startTimeStr)) {
                return this.formatReturnData("缺少参数");
            }
            if (!CheckUtils.isValidDate(startTimeStr, "yyyy-MM-dd HH:mm:ss")) {
                return this.formatReturnData("日期格式不正确");
            }
            String startTime = startTimeStr.substring(0, 17) + "00";
            String defaultEndTime = DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss");
            String endTime = DataConversionUtil.getStrFromMapOrSetDefaultValue("endTime", defaultEndTime, params);

            String mStr = DataConversionUtil.getStrFromMapOrSetDefaultValue("m", "3", params);
            int m = Integer.parseInt(mStr);

            //Δt
            String dtStr = DataConversionUtil.getStrFromMapOrSetDefaultValue("dt", "30", params);
            int dt = Integer.parseInt(dtStr);

            //n
            String nStr = DataConversionUtil.getStrFromMapOrSetDefaultValue("n", "1", params);
            int n = Integer.parseInt(nStr);

            //a
            String aStr = DataConversionUtil.getStrFromMapOrSetDefaultValue("a", "0.5", params);
            double a = Double.valueOf(aStr);

            //计算库里获取数据，如果存在数据，则直接使用，如果无则计算
            /*long count = electromagneticService.deviationLast(mineId, workingFace, startTime, endTime, m, dt,n);
            data.put("total", count);*/
            List<Map<String, Object>> resultList =
                electromagneticService.querydeviationLast(mineId, workingFace, startTime, endTime, m, dt, n, a);
            data.put("list", resultList);
            return this.formatReturnData(data);

        } catch (Exception e) {
            logger.error("ElectromagneticController-getDeviation:", e);
            return this.formatReturnData(e.getMessage());
        } catch (Throwable throwable) {
            logger.error("ElectromagneticController-getDeviation:", throwable);
            return this.formatReturnData(throwable.getMessage());
        }
    }

    /**
     * @Description: n小时偏离异常累计时间H
     * @Param: [params, request, response]
     * @return: java.util.Map<java.lang.String   ,   java.lang.Object>
     * @Author: ChengQi
     * @Date: 2018/12/20
     */
    @RequestMapping("/deviationLastTotal") public Map<String, Object> deviationLastTotal(
        @RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> data = new HashMap<String, Object>();
            //矿区id
            String mineId = DataConversionUtil.getStrFromMap("mineId", params);
            //工作面
            String workingFace = DataConversionUtil.getStrFromMap("workingFace", params);

            String startTimeStr = DataConversionUtil.getStrFromMap("startTime", params);
            //矿区id、工作面必传
            if (StringUtils.isBlank(mineId) || StringUtils.isBlank(workingFace) || StringUtils.isBlank(startTimeStr)) {
                return this.formatReturnData("缺少参数");
            }
            if (!CheckUtils.isValidDate(startTimeStr, "yyyy-MM-dd HH:mm:ss")) {
                return this.formatReturnData("日期格式不正确");
            }
            String startTime = startTimeStr.substring(0, 17) + "00";
            String defaultEndTime = DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss");
            String endTime = DataConversionUtil.getStrFromMapOrSetDefaultValue("endTime", defaultEndTime, params);

            String mStr = DataConversionUtil.getStrFromMapOrSetDefaultValue("m", "3", params);
            int m = Integer.parseInt(mStr);

            //Δt
            String dtStr = DataConversionUtil.getStrFromMapOrSetDefaultValue("dt", "30", params);
            int dt = Integer.parseInt(dtStr);

            //n
            String nStr = DataConversionUtil.getStrFromMapOrSetDefaultValue("n", "1", params);
            int n = Integer.parseInt(nStr);

            //a
            String aStr = DataConversionUtil.getStrFromMapOrSetDefaultValue("a", "0.5", params);
            double a = Double.valueOf(aStr);
            //计算库里获取数据，如果存在数据，则直接使用，如果无则计算
            //long count = electromagneticService.countWebDeviation(mineId, workingFace, startTime, endTime, m, dt,n);
            //data.put("total", count);
            List<Map<String, Object>> resultList =
                electromagneticService.deviationLastTotal(mineId, workingFace, startTime, endTime, m, dt, n, a);
            data.put("list", resultList);
            return this.formatReturnData(data);

        } catch (Exception e) {
            logger.error("ElectromagneticController-getDeviation:", e);
            return this.formatReturnData(e.getMessage());
        } catch (Throwable throwable) {
            logger.error("ElectromagneticController-getDeviation:", throwable);
            return this.formatReturnData(throwable.getMessage());
        }
    }

    /**
     * @Description: n小时偏离异常频次N
     * @Param: [params, request, response]
     * @return: java.util.Map<java.lang.String   ,   java.lang.Object>
     * @Author: ChengQi
     * @Date: 2018/12/20
     */
    @RequestMapping("/deviationFrequency") public Map<String, Object> deviationFrequency(
        @RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> data = new HashMap<String, Object>();
            //矿区id
            String mineId = DataConversionUtil.getStrFromMap("mineId", params);
            //工作面
            String workingFace = DataConversionUtil.getStrFromMap("workingFace", params);

            String startTimeStr = DataConversionUtil.getStrFromMap("startTime", params);
            //矿区id、工作面必传
            if (StringUtils.isBlank(mineId) || StringUtils.isBlank(workingFace) || StringUtils.isBlank(startTimeStr)) {
                return this.formatReturnData("缺少参数");
            }
            if (!CheckUtils.isValidDate(startTimeStr, "yyyy-MM-dd HH:mm:ss")) {
                return this.formatReturnData("日期格式不正确");
            }
            String startTime = startTimeStr.substring(0, 17) + "00";
            String defaultEndTime = DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss");
            String endTime = DataConversionUtil.getStrFromMapOrSetDefaultValue("endTime", defaultEndTime, params);
            //m
            String mStr = DataConversionUtil.getStrFromMapOrSetDefaultValue("m", "3", params);
            int m = Integer.parseInt(mStr);

            //Δt
            String dtStr = DataConversionUtil.getStrFromMapOrSetDefaultValue("dt", "30", params);
            int dt = Integer.parseInt(dtStr);

            //n
            String nStr = DataConversionUtil.getStrFromMapOrSetDefaultValue("n", "1", params);
            int n = Integer.parseInt(nStr);

            //a
            String aStr = DataConversionUtil.getStrFromMapOrSetDefaultValue("a", "0.5", params);
            double a = Double.valueOf(aStr);

            //计算库里获取数据，如果存在数据，则直接使用，如果无则计算
            /*long count = electromagneticService.countWebDeviation(mineId, workingFace, startTime, endTime, m, dt,n);
            data.put("total", count);*/
            List<Map<String, Object>> resultList =
                electromagneticService.deviationFrequency(mineId, workingFace, startTime, endTime, m, dt, n, a);
            data.put("list", resultList);
            return this.formatReturnData(data);
        } catch (Exception e) {
            logger.error("ElectromagneticController-getDeviation:", e);
            return this.formatReturnData(e.getMessage());
        } catch (Throwable throwable) {
            logger.error("ElectromagneticController-getDeviation:", throwable);
            return this.formatReturnData(throwable.getMessage());
        }
    }

    /**
     * @Description: 综合预警
     * @Param: [params, request, response]
     * @return: java.util.Map<java.lang.String , java.lang.Object>
     * @Author: ChengQi
     * @Date: 2019/1/3
     */
    @RequestMapping("/comprehensiveWarning") public Map<String, Object> comprehensiveWarning(
        @RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> data = new HashMap<String, Object>();

            // 矿区id
            String mineId = DataConversionUtil.getStrFromMap("mineId", params);

            // 开始时间
            String startTime = DataConversionUtil.getStrFromMap("startTime", params);

            if (StringUtils.isBlank(mineId) || StringUtils.isBlank(startTime)) {
                return this.formatReturnData("缺少参数");
            }
            if (!CheckUtils.isValidDate(startTime, "yyyy-MM-dd HH:mm:ss")) {
                return this.formatReturnData("日期格式不正确");
            }
            // 结束时间
            String defaultEndTime = DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss");
            String endTime = DataConversionUtil.getStrFromMapOrSetDefaultValue("endTime", defaultEndTime, params);

            Map<String, Object> results = electromagneticService.comprehensiveWarning(mineId, startTime, endTime);
            data.put("list", results);
            return this.formatReturnData(data);
        } catch (Exception e) {
            logger.error("MicroseismController-microseismRealTime:", e);
            return this.formatReturnData(e.getMessage());
        } catch (Throwable throwable) {
            logger.error("MicroseismController-microseismRealTime:", throwable);
            return this.formatReturnData(throwable.getMessage());
        }
    }

}
